﻿$(document).ready(function () {
    // alert(Cookies.get('gxskCommunicateRange'));
    // Cookies.set('gxskCommunicateRange', "all", { expires: 7, path: '' });
    fetchCommunicates(1);
    //switchToAllState();

    $("#add-communicate-theme-btn").click(function () {
        if (addCommunicateThemeValidate()) {
            //console.log( $("#communicate-content").val());
            $.ajax({
                type: "POST",
                data: { Title: $("#communicate-title").val(), Content: $("#communicate-content").val()},
                url: "../Handle/ExchangeHandlerService.ashx?method=Add_New_ExchangeTheme",
                dataType: "json",
                success: function (data) {
                    //console.log(data);
                    if(1 == data.MessageType) {
                        // alert("消息删除成功！");
                        $("#CommunicateThemeModal").modal("hide");
                        $("#dialog-modal-label").text("新交流主题添加成功！");
                        $("#DialogModal").modal("show");
                        fetchCommunicates(1);
                    } else {
                        // alert("消息删除失败！");
                        $("#dialog-modal-label").text("新交流主题添加失败！" + data.MessageContent);
                        $("#DialogModal").modal("show");
                        return;
                    }
                }
            });
        }
    });

    $("#edit-communicate-theme-btn").click(function () {
        if (addCommunicateThemeValidate()) {
            // console.log( $("#edit-communicate-theme-btn").attr("value"));
            $.ajax({
                type: "POST",
                data: { Title: $("#communicate-title").val(), Content: $("#communicate-content").val(), ExchangeID: $("#edit-communicate-theme-btn").attr("value")},
                url: "../Handle/ExchangeHandlerService.ashx?method=Modify_One_ExchangeTheme_Info",
                dataType: "json",
                success: function (data) {
                    // console.log(data);
                    fetchCommunicates($("#communicate-list-pagination").pagination("getCurrentPage"));
                    $("#CommunicateThemeModal").modal("hide");
                }
            });
        }
    });

    $("#communicate-theme-btn").click(function () {
        $("#add-communicate-theme-btn").removeClass("hidden");
        $("#edit-communicate-theme-btn").addClass("hidden");
        $("#communicate-title").val("");
        $("#communicate-content").val("");
        $("#modal-title").html("添加新主题");
        $("#CommunicateThemeModal").modal("show");
    });

    $("#my-theme-btn").click(function () {
        Cookies.set('gxskCommunicateRange', "my", { expires: 7, path: '' });
        fetchCommunicates(1);
    });

    $("#all-theme-btn").click(function () {
        Cookies.set('gxskCommunicateRange', "all", { expires: 7, path: '' });
        fetchCommunicates(1);
    });

    $("#add-comment-btn").click(function(e) {
        // alert($("#curr-communicate-theme-id").val());
        // alert($("#content-text").val());
        if (addCommentValidate()) {
                $.ajax({
                type: "POST",
                data: {Content: $("#content-text").val(), EXID: $("#curr-communicate-theme-id").val()},
                url: "../Handle/ExchangeHandlerService.ashx?method=Add_New_ExchangeEvalInfo",
                dataType: "json",
                success: function (data) {
                    if (-1 == data.MessageType) {
                        alert(data.MessageContent);
                    } else {
                        alert(data.MessageContent);
                        $("#CommunicateDetailModal").modal("hide");
                        fetchCommunicates($("#communicate-list-pagination").pagination("getCurrentPage"));
                    }
                }
            });
        }
    });

    $('#CommunicateDetailModal').on('shown.bs.modal', function (event) {
        // var exid = $(event.relatedTarget).data('exid');
        //alert("exid");
        // console.log($("#comment-list").height());
        if ($("#comment-list").height() > 300) {
            $("#comment-list").height(300);
        }
    });

    $(document)
        .on('click', '.edit-btn', function(e) {
            e.stopPropagation();
            // alert($(this).attr("value"));
            
            $.ajax({
                type: "GET",
                data: { ExchangeID: $(this).attr("value")},
                url: "../Handle/ExchangeHandlerService.ashx?method=Get_One_ExchangeTheme_Info_From_EXID",
                dataType: "json",
                success: function (data) {
                    //console.log(data);
                    var item = data.rows[0];
                    $("#communicate-title").val(item["Title"]);
                    $("#communicate-content").val(item["Content"]);
                    $("#add-communicate-theme-btn").addClass("hidden");
                    $("#edit-communicate-theme-btn").removeClass("hidden");
                    $("#edit-communicate-theme-btn").attr("value", item["EXID"]);
                    $("#modal-title").html("编辑该主题");
                    $("#CommunicateThemeModal").modal("show");
                }
            });
            
            // window.open("Book.aspx?BID="+$(this).attr("value"));      
        })
        .on('click', '.panel', function(e){
            e.stopPropagation();
            $("#comment-list").height("auto");
            $("#curr-communicate-theme-id").val($(this).attr("value"));
            $.ajax({
                type: "GET",
                data: { ExchangeID: $(this).attr("value")},
                url: "../Handle/ExchangeHandlerService.ashx?method=Get_One_ExchangeTheme_Info_From_EXID",
                dataType: "json",
                success: function (data) {
                    
                    var item = data.rows[0];
                    // console.log(item);
                    $("#detail-communicate-title").html("<h4>" + item["Title"] +"<small> / " + item["Fname"] + " / " + item["short_signDate"] + "</small></h4>");
                    $("#detail-communicate-content").html(item["Content"]);
                }
            });
            $.ajax({
                type: "GET",
                data: { ExchangeID: $(this).attr("value"), IsAll: "PART", PageIndex: 1, PageSize: 20},
                url: "../Handle/ExchangeHandlerService.ashx?method=Get_ExchangeEvalInfo_List",
                dataType: "json",
                success: function (data) {
                    //console.log(data);
                    $("#comment-list").html(getCommentListOutputHtml(data.rows));
                    $("#content-text").val("");
                    $("#CommunicateDetailModal").modal("show");
                }
            });
            
        })
});

function fetchCommunicates(pageIndex) {
    var method = "";
    if ("all" == Cookies.get('gxskCommunicateRange') || undefined == Cookies.get('gxskCommunicateRange')) {
        method = "Get_ExchangeTheme_List";
        switchToAllState();
    } else if ("my" == Cookies.get('gxskCommunicateRange')) {
        method = "Get_One_Family_All_ExchangeTheme_List";
        switchToMyState();
    }
    $.ajax({
        type: "GET",
        data: { PageSize : 12, PageIndex : pageIndex},
        url: "../Handle/ExchangeHandlerService.ashx?method="+method,
        dataType: "json",
        success: function (data) {
            // console.log(data.rows);
            $("#communicate-list").html(getCommunicateListOutputHtml(data.rows, Cookies.get('gxskCommunicateRange')));
            $("#communicate-list-pagination").pagination({
                items: data.RecordCount,
                itemsOnPage: 12,
                currentPage: pageIndex,
                displayedPages: 3,
                onPageClick: changeCommunicateListPage,
                edges: 0,
                prevText: "<",
                nextText: ">",
                cssStyle: 'light-theme',
            });
        }
    });
}
function changeCommunicateListPage() {
    fetchCommunicates($("#communicate-list-pagination").pagination("getCurrentPage"));
}
function switchToMyState() {
    $("#all-theme-btn").removeClass("btn-default");
    $("#all-theme-btn").addClass("btn-info");
    $("#my-theme-btn").removeClass("btn-info");
    $("#my-theme-btn").addClass("btn-default");
}

function switchToAllState() {
    $("#my-theme-btn").removeClass("btn-default");
    $("#my-theme-btn").addClass("btn-info");
    $("#all-theme-btn").removeClass("btn-info");
    $("#all-theme-btn").addClass("btn-default");
}

function addCommunicateThemeValidate() {
    return $("#add-communicate-theme-form").validate({
        errorClass: "warning",
        errorPlacement: function(error, element) {
            if (element.is(":checkbox")){  
                error.insertAfter(element.parent().parent());
            }else{  
                error.insertAfter(element.parent()); 
            }  
        }, 
        rules: {
            communicateTitle: {
                required: true,
                minlength: 5,
                maxlength: 50
            },
            communicateContent: {
                required: true,
                minlength: 10,
                maxlength: 500
            }
        },
        messages: {
            communicateTitle: {
                required: "主题必填",
                minlength: "主题不能少于5个字",
                maxlength: "主题最大长度不能大于50个字"
            },
            communicateContent: {
                required: "内容必填",
                minlength: "内容不能少于10个字",
                maxlength: "内容不能大于500个字"
            }
        }
    }).form();
}

function addCommentValidate() {
    return $("#add-comment-form").validate({
        errorClass: "warning",
        errorPlacement: function(error, element) {
            if (element.is(":checkbox")){  
                error.insertAfter(element.parent().parent());
            }else{  
                error.insertAfter(element.parent()); 
            }  
        }, 
        rules: {
            contentText: {
                required: true,
                minlength: 10,
                maxlength: 500
            }
        },
        messages: {
            contentText: {
                required: "内容必填",
                minlength: "内容不能少于10个字",
                maxlength: "内容不能大于500个字"
            }
        }
    }).form();
}

function getCommunicateListOutputHtml(items, range) {
    var outputHtml = "";
    var outputClass = "col-xs-12 col-md-4 col-sm-6";
    
    for (var i = 0; i < items.length; i++) {
        var item = items[i];
    
        var panelCss = "panel-primary";
        var panelTitleAdd = "普通";
        if (item["IsTop"]) {
            panelCss = "panel-danger";
            panelTitleAdd = "置顶";
        }
        if (item["IsHidden"]) {
            panelTitleAdd += " | 隐藏";
        }
        // console.log(item);
        var editBtn = "";
        if ("my" == range && false == item["IsHidden"]) {
            editBtn = "<div style='float:right'><i class='glyphicon glyphicon-edit edit-btn' value='" + item["EXID"] + "'></i></div>";
        }

        //var dataContent = "<p><small>" + item["Author"] + " / " + item["PYM"] + " / " + item["Press"] + "</small></p><small>" + subStrToLimitLength(item["Descript"], 150) + "</small>";
        //var dataContent = "<p><small>" + item["Author"] + " / " + item["PYM"] + " / " + item["Press"] + "</small></p>";
        outputHtml += "<div class='" + outputClass + "' style='padding-left:0px; padding-right:10px'><div class='panel "+panelCss+"' value='" + item["EXID"] + "' data-exid='" + item["EXID"] + "'>" +
        "<div class='panel-heading'><" + panelTitleAdd + "> " + subStrToLimitLength(item["Title"], 14) + editBtn +"</div>" +
        "<div class='panel-body' style='height:85px'><small>" + subStrToLimitLength(item["Content"], 70) + "</small></div>" +
        "<div class='panel-footer'>" + item["Fname"] + "——4月15日——" + item["ReplyCount"] + "人跟帖</div>" +
        "</div></div>";
    }
    return outputHtml;
}

function getCommentListOutputHtml(items) {
    var outputHtml = "";
    
    
    for (var i = 0; i < items.length; i++) {
        var item = items[i];
        var topClass = "";
        if (item['isTop']) {
            topClass = "";
        }

        outputHtml += "<p>" + item["Fname"] +"：<small>" + item["Content"] + " /" + item["short_signDate"] + "/</small></p>";
    }
    return outputHtml;
}

